<template>
  <div id="microPageCreate" v-loading="dataLoading">
    <!--左侧工具栏-->
    <div class="zonetoolsBox">
      <el-card class="tools-box">
        <div slot="header">
          <span>组件库</span>
        </div>
        <el-tabs
          :value="activateTab"
          @tab-click="tabClick"
          type="border-card"
          tab-position="left"
          style="
            height: 100%;
            border-top-right-radius: 0;
            border-right: none;
            border-top: none;
          "
        >
          <el-tab-pane name="图片" label="图片">
            <images-list
              :activate="activateTab === '图片'"
              @selectedImg="selectedImg"
            ></images-list>
          </el-tab-pane>
          <el-tab-pane name="文字" label="文字">
            <text-list
              :activate="activateTab === '文字'"
              @selectedText="selectedText"
            ></text-list>
          </el-tab-pane>
          <el-tab-pane name="视频" label="视频">
            <video-list
              :activate="activateTab === '视频'"
              @selectedVideo="selectedVideo"
            ></video-list>
          </el-tab-pane>
          <el-tab-pane name="电话" label="电话">
            <phone-list
              :activate="activateTab === '电话'"
              @selectedPhone="selectedPhone"
            ></phone-list>
          </el-tab-pane>
          <el-tab-pane name="网址" label="网址">
            <link-list
              :activate="activateTab === '网址'"
              @selectedLink="selectedLink"
            ></link-list>
          </el-tab-pane>
          <el-tab-pane name="地图导航" label="地图导航">
            <map-list
              :activate="activateTab === '地图导航'"
              @selectedMap="selectedMap"
            ></map-list>
          </el-tab-pane>
          <el-tab-pane name="背景音乐" label="背景音乐">
            <music-list
              :activate="activateTab === '背景音乐'"
              @selectedMusic="selectedMusic"
            ></music-list>
          </el-tab-pane>
          <el-tab-pane name="背景图片" label="背景图片">
            <background-list
              :activate="activateTab === '背景图片'"
              @selectedBackgroundImg="selectedBackgroundImg"
            ></background-list>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <!--主要操作栏-->
    <div class="zone-operation">
      <div class="phone-div">
        <div class="phone-top">
          <div class="phone-camera"></div>
          <div class="phone-speaker"></div>
        </div>
        <div id="working_space" class="phone-middle">
          <div
            :class="{
              background_music_icon:
                templateData.background_music && !audioPlaying,
              background_music_icon_play:
                templateData.background_music && audioPlaying,
            }"
            @click="playOrPauseMusic"
          >
            <i></i>
          </div>
          <div
            v-if="workingData !== null"
            class="item_space"
            :style="{
              backgroundImage:
                'url(' +
                baseURL +
                (workingData.background_img ||
                  templateData.background_img ||
                  '') +
                ')',
            }"
          >
            <div v-for="(item, index) in workingData.items" :key="index">
              <!--图片模块-->
              <template v-if="item.type === 1">
                <VueDragResize
                  :class="['animated', item.dynamicEffect]"
                  :style="{
                    animationDuration: item.dynamicDuration + 's',
                    animationDelay: item.dynamicDelay + 's',
                  }"
                  :isActive="item.isActive"
                  :z="item.zIndex"
                  :w="item.width"
                  :h="item.height"
                  :y="item.top"
                  :x="item.left"
                  :minw="20"
                  :minh="20"
                  v-on:resizing="resize"
                  v-on:dragging="resize"
                  @dragging="vueDragResizeDragging"
                  @activated="vueDragResizeActivated(item)"
                >
                  <i
                    v-if="item.isActive || false"
                    class="exitEditMode"
                    @click="vueDragResizeDeactivated"
                    style=""
                    >退出编辑</i
                  >
                  <el-button
                    v-if="item.isActive || false"
                    class="deleteBtn"
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    @click="deleteModule(index)"
                  ></el-button>
                  <img
                    class="module-images"
                    :style="{
                      width: item.width - 10 + 'px',
                      height: item.height - 10 + 'px',
                      backgroundImage: 'url(' + (baseURL + item.theme) + ')',
                      padding: '5px',
                    }"
                    :src="
                      item.src === ''
                        ? baseURL + 'logo/logo3.png'
                        : baseURL + item.src
                    "
                  />
                </VueDragResize>
              </template>
              <!--文字模块-->
              <template v-if="item.type === 2">
                <VueDragResize
                  :class="['animated', item.dynamicEffect]"
                  :style="{
                    animationDuration: item.dynamicDuration + 's',
                    animationDelay: item.dynamicDelay + 's',
                  }"
                  :isActive="item.isActive"
                  :z="item.zIndex"
                  :w="item.width"
                  :h="item.height"
                  :y="item.top"
                  :x="item.left"
                  :minw="20"
                  :minh="20"
                  v-on:resizing="resize"
                  v-on:dragging="resize"
                  @dragging="vueDragResizeDragging"
                  @activated="vueDragResizeActivated(item)"
                >
                  <i
                    v-if="item.isActive || false"
                    class="exitEditMode"
                    @click="vueDragResizeDeactivated"
                    style=""
                    >退出编辑</i
                  >
                  <el-button
                    v-if="item.isActive || false"
                    class="deleteBtn"
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    @click="deleteModule(index)"
                  ></el-button>
                  <span
                    class="module-text"
                    :style="{
                      width: item.width + 'px',
                      height: item.height + 'px',
                      color: item.text_color,
                      fontSize: item.text_size + 'px',
                      backgroundImage: 'url(' + (baseURL + item.theme) + ')',
                    }"
                  >
                    {{ item.text }}
                  </span>
                </VueDragResize>
              </template>
              <!--视频模块-->
              <template v-if="item.type === 3">
                <VueDragResize
                  :class="['animated', item.dynamicEffect]"
                  :style="{
                    animationDuration: item.dynamicDuration + 's',
                    animationDelay: item.dynamicDelay + 's',
                  }"
                  :isActive="item.isActive"
                  :z="item.zIndex"
                  :w="item.width"
                  :h="item.height"
                  :y="item.top"
                  :x="item.left"
                  :minw="20"
                  :minh="20"
                  v-on:resizing="resize"
                  v-on:dragging="resize"
                  @dragging="vueDragResizeDragging"
                  @activated="vueDragResizeActivated(item)"
                >
                  <i
                    v-if="item.isActive || false"
                    class="exitEditMode"
                    @click="vueDragResizeDeactivated"
                    style=""
                    >退出编辑</i
                  >
                  <el-button
                    v-if="item.isActive || false"
                    class="deleteBtn"
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    @click="deleteModule(index)"
                  ></el-button>
                  <video
                    class="module-video"
                    :src="
                      item.src === ''
                        ? baseURL + 'logo/logo3.png'
                        : baseURL + item.src
                    "
                    controls="controls"
                    :style="{
                      width: item.width + 'px',
                      height: item.height + 'px',
                    }"
                  >
                    您的浏览器不支持 video 标签。
                  </video>
                </VueDragResize>
              </template>
              <!--电话模块-->
              <template v-if="item.type === 4">
                <VueDragResize
                  :class="['animated', item.dynamicEffect]"
                  :style="{
                    animationDuration: item.dynamicDuration + 's',
                    animationDelay: item.dynamicDelay + 's',
                  }"
                  :isActive="item.isActive"
                  :z="item.zIndex"
                  :w="item.width"
                  :h="item.height"
                  :y="item.top"
                  :x="item.left"
                  :minw="20"
                  :minh="20"
                  v-on:resizing="resize"
                  v-on:dragging="resize"
                  @dragging="vueDragResizeDragging"
                  @activated="vueDragResizeActivated(item)"
                >
                  <i
                    v-if="item.isActive || false"
                    class="exitEditMode"
                    @click="vueDragResizeDeactivated"
                    style=""
                    >退出编辑</i
                  >
                  <el-button
                    v-if="item.isActive || false"
                    class="deleteBtn"
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    @click="deleteModule(index)"
                  ></el-button>
                  <div
                    :class="'phone-theme ' + item.theme"
                    :style="{
                      width: item.width + 'px',
                      height: item.height + 'px',
                    }"
                  >
                    <div
                      class="left-side"
                      :style="{
                        background:
                          '#52cadb url(' +
                          baseURL +
                          'microPageModulesResources/images/multiPage/phone/' +
                          item.theme +
                          '-l.png' +
                          ') no-repeat',
                      }"
                    >
                      <i class="el-icon-phone"></i>
                    </div>
                    <div
                      class="right-side"
                      :style="{
                        background:
                          '#52cadb url(' +
                          baseURL +
                          'microPageModulesResources/images/multiPage/phone/' +
                          item.theme +
                          '-r.png' +
                          ') no-repeat',
                      }"
                    >
                      <div>{{ item.name }}</div>
                      <div>{{ item.text }}</div>
                    </div>
                  </div>
                </VueDragResize>
              </template>
              <!--链接模块-->
              <template v-if="item.type === 5">
                <VueDragResize
                  :class="['animated', item.dynamicEffect]"
                  :style="{
                    animationDuration: item.dynamicDuration + 's',
                    animationDelay: item.dynamicDelay + 's',
                  }"
                  :isActive="item.isActive"
                  :z="item.zIndex"
                  :w="item.width"
                  :h="item.height"
                  :y="item.top"
                  :x="item.left"
                  :minw="20"
                  :minh="20"
                  v-on:resizing="resize"
                  v-on:dragging="resize"
                  @dragging="vueDragResizeDragging"
                  @activated="vueDragResizeActivated(item)"
                >
                  <i
                    v-if="item.isActive || false"
                    class="exitEditMode"
                    @click="vueDragResizeDeactivated"
                    style=""
                    >退出编辑</i
                  >
                  <el-button
                    v-if="item.isActive || false"
                    class="deleteBtn"
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    @click="deleteModule(index)"
                  ></el-button>
                  <div
                    :class="'link-theme ' + item.theme"
                    :style="{
                      width: item.width + 'px',
                      height: item.height + 'px',
                    }"
                  >
                    <div
                      class="left-side"
                      :style="{
                        background:
                          '#52cadb url(' +
                          baseURL +
                          'microPageModulesResources/images/multiPage/link/' +
                          item.theme +
                          '-l.png' +
                          ') no-repeat',
                      }"
                    >
                      <i class="el-icon-link"></i>
                    </div>
                    <div
                      class="right-side"
                      :style="{
                        background:
                          '#52cadb url(' +
                          baseURL +
                          'microPageModulesResources/images/multiPage/link/' +
                          item.theme +
                          '-r.png' +
                          ') no-repeat',
                      }"
                    >
                      <div>{{ item.name }}</div>
                    </div>
                  </div>
                </VueDragResize>
              </template>
              <!--地图模块-->
              <template v-if="item.type === 6">
                <VueDragResize
                  :class="['animated', item.dynamicEffect]"
                  :style="{
                    animationDuration: item.dynamicDuration + 's',
                    animationDelay: item.dynamicDelay + 's',
                  }"
                  :isActive="item.isActive"
                  :z="item.zIndex"
                  :w="item.width"
                  :h="item.height"
                  :y="item.top"
                  :x="item.left"
                  :minw="20"
                  :minh="20"
                  v-on:resizing="resize"
                  v-on:dragging="resize"
                  @dragging="vueDragResizeDragging"
                  @activated="vueDragResizeActivated(item)"
                >
                  <i
                    v-if="item.isActive || false"
                    class="exitEditMode"
                    @click="vueDragResizeDeactivated"
                    style=""
                    >退出编辑</i
                  >
                  <el-button
                    v-if="item.isActive || false"
                    class="deleteBtn"
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    @click="deleteModule(index)"
                  ></el-button>
                  <baidu-map
                    :class="'map-theme ' + item.theme"
                    :style="{
                      width: item.width + 'px',
                      height: item.height + 'px',
                    }"
                    :point="[item.lng, item.lat]"
                  ></baidu-map>
                </VueDragResize>
              </template>
            </div>
          </div>
        </div>
        <div class="phone-bottom">
          <div class="phone-botton"></div>
        </div>
      </div>
    </div>
    <!--属性栏-->
    <div class="zone-attributes">
      <el-card class="tools-box">
        <div slot="header">
          <span>属性</span>
          <el-button
            type="primary"
            size="small"
            style="position: absolute; right: 20px; top: 13px"
            @click="saveAndPublish"
            >保存发布
          </el-button>
        </div>
        <el-tabs
          type="border-card"
          tab-position="top"
          style="
            height: 100%;
            border-top-left-radius: 0;
            border-left: none;
            border-top: none;
          "
        >
          <el-tab-pane label="页码">
            <el-tree
              class="page-list"
              highlight-current
              @node-click="treeNodeClick"
              :data="templateData.pages"
              ref="pageTree"
              :render-content="treeRenderContent"
              draggable
              :allow-drop="treeAllowDrop"
              node-key="index"
              @node-drop="treeNodeDrop"
            ></el-tree>
            <div style="margin: 0px auto; text-align: center; margin-top: 5px">
              <el-button
                @click="addPage"
                style="
                  width: 30px;
                  height: 30px;
                  line-height: 20px;
                  padding: 5px;
                "
                type="primary"
                icon="el-icon-plus"
                circle
              ></el-button>
              <el-button
                @click="deletePage"
                :disabled="workingData === null"
                style="
                  width: 30px;
                  height: 30px;
                  line-height: 20px;
                  padding: 5px;
                "
                type="danger"
                icon="el-icon-delete"
                circle
              ></el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane label="属性">
            <el-form ref="form" :model="itemAttr" label-width="88px">
              <el-form-item label="组件类型：">{{
                itemAttr.type
              }}</el-form-item>
              <el-form-item v-if="itemAttr.type === '图片'" label="更换图片：">
                <el-upload
                  class="upload-demo"
                  accept=".jpg,.png,.gif"
                  :data="uploadParamates"
                  :show-file-list="false"
                  :on-success="imgUploadSuccess"
                  :before-upload="beforeImgUpload"
                  :action="this.baseURL + 'files/upPicture'"
                  :disabled="itemAttr.type !== '图片'"
                >
                  <el-button
                    size="mini"
                    type="primary"
                    :disabled="itemAttr.type !== '图片'"
                    >上传图片
                  </el-button>
                </el-upload>
              </el-form-item>
              <el-form-item v-if="itemAttr.type === '视频'" label="更换视频：">
                <el-upload
                  class="upload-demo"
                  accept=".mp4,.ogg"
                  :data="uploadParamates"
                  :show-file-list="false"
                  :on-success="videoUploadSuccess"
                  :before-upload="beforeVideoUpload"
                  :action="this.baseURL + 'files/upPicture'"
                  :disabled="itemAttr.type !== '视频'"
                >
                  <el-button
                    size="mini"
                    type="primary"
                    :disabled="itemAttr.type !== '视频'"
                    >上传视频
                  </el-button>
                </el-upload>
              </el-form-item>
              <el-form-item v-if="itemAttr.type === '文字'" label="文字内容：">
                <el-input
                  size="mini"
                  type="textarea"
                  :rows="4"
                  resize="none"
                  v-model="tempActivatedItem.text"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item v-if="itemAttr.type === '电话'" label="名字：">
                <el-input
                  size="mini"
                  v-model="tempActivatedItem.name"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item v-if="itemAttr.type === '电话'" label="号码：">
                <el-input
                  size="mini"
                  v-model="tempActivatedItem.text"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item v-if="itemAttr.type === '网址'" label="显示名字：">
                <el-input
                  size="mini"
                  v-model="tempActivatedItem.name"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item v-if="itemAttr.type === '网址'" label="转跳地址：">
                <el-input
                  size="mini"
                  v-model="tempActivatedItem.text"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item v-if="itemAttr.type === '地图导航'" label="经度：">
                <el-input
                  size="mini"
                  v-model="tempActivatedItem.lng"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item v-if="itemAttr.type === '地图导航'" label="纬度：">
                <el-input
                  size="mini"
                  v-model="tempActivatedItem.lat"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item
                v-if="itemAttr.type === '地图导航'"
                label="经纬度拾取"
              >
                <a
                  href="http://api.map.baidu.com/lbsapi/getpoint/"
                  target="_blank"
                  style="text-decoration: underline"
                  >百度经纬度拾取</a
                >
              </el-form-item>
              <el-form-item v-if="itemAttr.type === '文字'" label="文字颜色：">
                <el-color-picker
                  style="vertical-align: middle; margin-top: -4px"
                  size="mini"
                  v-model="tempActivatedItem.text_color"
                ></el-color-picker>
              </el-form-item>
              <el-form-item v-if="itemAttr.type === '文字'" label="文字大小：">
                <el-input-number
                  size="mini"
                  v-model="tempActivatedItem.text_size"
                  :min="12"
                  :max="26"
                  label="文字大小"
                ></el-input-number>
              </el-form-item>
              <el-form-item label="动画效果：">
                <template v-if="tempActivatedItem !== null">
                  <el-select
                    size="mini"
                    :disabled="tempActivatedItem === null"
                    v-model="tempActivatedItem.dynamicEffect"
                    placeholder="请选择动画效果"
                  >
                    <el-option-group
                      v-for="group in animatedData"
                      :key="group.name"
                      :label="group.name"
                    >
                      <el-option
                        v-for="(item, index) in group.child"
                        :key="index"
                        :label="item.name"
                        :value="item.value"
                      ></el-option>
                    </el-option-group>
                  </el-select>
                </template>
                <template v-else>
                  <el-select
                    size="mini"
                    :disabled="tempActivatedItem === null"
                    v-model="tempValue"
                    placeholder="请选择动画效果"
                  >
                    <el-option-group
                      v-for="group in animatedData"
                      :key="group.name"
                      :label="group.name"
                    >
                      <el-option
                        v-for="(item, index) in group.child"
                        :key="index"
                        :label="item.name"
                        :value="item.value"
                      ></el-option>
                    </el-option-group>
                  </el-select>
                </template>
              </el-form-item>
              <el-form-item label="动画时间：">
                <template v-if="tempActivatedItem !== null">
                  <el-input-number
                    size="mini"
                    :disabled="tempActivatedItem === null"
                    :precision="2"
                    v-model="tempActivatedItem.dynamicDuration"
                    :min="1"
                    :max="60"
                    label="动画持续时间"
                  ></el-input-number>
                </template>
                <template v-else>
                  <el-input-number
                    size="mini"
                    :disabled="tempActivatedItem === null"
                    v-model="tempValue2"
                    :min="1"
                    :max="60"
                    label="动画持续时间"
                  ></el-input-number>
                </template>
              </el-form-item>
              <el-form-item label="动画延期：">
                <template v-if="tempActivatedItem !== null">
                  <el-input-number
                    size="mini"
                    :disabled="tempActivatedItem === null"
                    :precision="2"
                    v-model="tempActivatedItem.dynamicDelay"
                    :min="1"
                    :max="60"
                    label="动画延迟开始时间"
                  ></el-input-number>
                </template>
                <template v-else>
                  <el-input-number
                    size="mini"
                    :disabled="tempActivatedItem === null"
                    v-model="tempValue3"
                    :min="0"
                    :max="60"
                    label="动画延迟开始时间"
                  ></el-input-number>
                </template>
              </el-form-item>
              <el-form-item label="位置辅助：">
                <div style="margin-top: -2px">
                  <el-button
                    :disabled="tempActivatedItem === null"
                    @click="horizonCenter"
                    size="mini"
                    round
                    type="primary"
                    >水平居中
                  </el-button>
                  <el-button
                    :disabled="tempActivatedItem === null"
                    @click="verticalCenter"
                    size="mini"
                    round
                    type="primary"
                    >垂直居中
                  </el-button>
                </div>
              </el-form-item>
              <span style="padding-left: 7px; font-size: 12px; color: #909399"
                >小提示：键盘上下左右按键也可以调整位置哦</span
              >
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <el-dialog
      title="微单页保存成功"
      :visible.sync="microPageDialogFormVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="microPageForm">
        <el-form-item
          label="微单页id，请记录下来，下次可以继续编辑该微单页"
          label-width="300"
        >
          <el-input
            v-model="microPageForm.microPageId"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="微单页地址" label-width="300">
          <el-input
            v-model="microPageForm.microPageSrc"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="microPageDialogFormVisible = false"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!--背景音乐-->
    <audio
      v-if="templateData.background_music"
      ref="audio"
      :loop="templateData.loop"
      :autoplay="templateData.autoPlay"
      :src="baseURL + templateData.background_music"
    ></audio>
  </div>
</template>

<script>
import Vue from "vue";
import VueDragResize from "vue-drag-resize";
import animatedData from "./json/animated.json";
import backgroundList from "./components/backgroundList.vue";
import imagesList from "./components/imagesList.vue";
import textList from "./components/textList.vue";
import videoList from "./components/videoList.vue";
import phoneList from "./components/phoneList.vue";
import linkList from "./components/linkList.vue";
import mapList from "./components/mapList.vue";
import musicList from "./components/musicList.vue";
import baiduMap from "@/components/baiduMap";

export default {
  name: "microPageCreate",
  components: {
    VueDragResize,
    imagesList,
    backgroundList,
    textList,
    videoList,
    phoneList,
    linkList,
    mapList,
    musicList,
    baiduMap,
  },
  computed: {},
  data() {
    return {
      baseURL: "/",
      dataLoading: false, // 加载中
      activateTab: "图片", // 左边组件库激活的面板
      templateData: {
        // 模板数据
        title: "",
        logo: "",
        background_img: "",
        background_music: "",
        loop: false, // 背景音乐循环播放
        autoPlay: false, // 背景音乐自动播放
        pages: [],
      },
      treeDefaultProps: {
        label: "label",
      },
      workingData: null,
      tempActivatedItem: null, // 临时保存激活的项
      itemAttr: {
        // 组件的属性
        type: "",
        horizonCenter: false,
        verticalCenter: false,
      },
      uploadSrc: this.baseURL + "files/upPicture", // 图片上传的地址
      uploadParamates: {
        // 图片上传携带的参数
        type: 1,
      },
      animatedData: animatedData, // 动画效果
      tempValue: "", // 临时变量，给那个啥的，勿删
      tempValue2: 2, // 临时变量，给那个啥的，勿删
      tempValue3: 0, // 临时变量，给那个啥的，勿删
      microPageDialogFormVisible: false, // 提交成功后弹出弹窗显示微单页信息
      microPageForm: {
        // 提交成功后后台返回微单页的信息
        microPageId: "",
        microPageSrc: "",
      },
      audioInstance: null, // 背景音乐
      audioPlaying: false, // 背景音乐播放中
    };
  },
  computed: {
    itemType: {
      get: function () {
        return null;
      },
      set: function (newVal) {},
    },
  },
  watch: {
    tempActivatedItem: {
      handler: "tempActivatedItemChange",
      deep: true,
    },
  },
  created() {},
  mounted() {
    //当有window之后再注册组件
    if (process.client) {
      Vue.component("VueDragResize", require("vue-drag-resize").default);
    }

    if (this.$route.query.id) {
      // TODO 这里应该根据ID去后端取数据
      this.getPageData(this.$route.query.id);
    } else {
      // TODO 这里应该根据选择模板不同，加载不同的json
      this.getTemplateData("template1.json");
    }

    // 监听键盘事件
    document.onkeydown = (e) => {
      if (this.tempActivatedItem !== null) {
        switch (window.event.keyCode) {
          case 38: // 上箭头
            this.tempActivatedItem.top -= 10;
            break;
          case 40: // 下箭头
            this.tempActivatedItem.top += 10;
            break;
          case 37: // 左箭头
            this.tempActivatedItem.left -= 10;
            break;
          case 39: // 右箭头
            this.tempActivatedItem.left += 10;
            break;
        }
      }
    };
    if (this.templateData.pages.length > 0) {
      this.$refs.pageTree.setCurrentKey(this.templateData.pages[0].index); // 设置默认勾选的页码
    }
  },
  methods: {
    /**
     * 加载模板数据
     * @param templateId 模板id
     **/
    getTemplateData(templateId) {
      let jsonData = require("./json/" + templateId);
      this.templateData = jsonData;
      this.initData();
    },
    /**
     * 加载json数据
     * @param pageId 模板id
     **/
    getPageData(pageId) {
      let arr = localStorage.getItem("myPage");
      if (arr !== null) {
        try {
          let tempArr = JSON.parse(arr);
          if (Array.isArray(tempArr)) {
            let tempObj = tempArr.find((t) => t.id === pageId);
            if (tempObj !== undefined && tempObj.hasOwnProperty("content")) {
              this.templateData = tempObj.content;
            } else {
              console.error("获取网页数据错误~");
            }
          }
        } catch (error) {
          console.error("获取网页数据错误~");
        }
      }
      this.initData();
    },
    /**
     * 初始化数据
     * @param templateId 模板id
     **/
    initData(templateId) {
      if (this.templateData.pages.length > 0) {
        this.workingData = this.templateData.pages[0];
      }
      // 判断背景音乐
      if (this.templateData.background_music) {
        if (this.audioInstance === null) {
          this.$nextTick(() => {
            this.audioInstance = this.$refs.audio;
          });
        }
      }
    },
    /**
     * 左边的组件库面板，激活面板触发事件
     **/
    tabClick(tab) {
      this.activateTab = tab.name;
    },
    /**
     * 页码调整，不允许拉到某个页码里面
     * @param moveNode
     * @param inNode
     * @param type
     * @returns {boolean}
     */
    treeAllowDrop(moveNode, inNode, type) {
      if (moveNode.level === 1 && inNode.level === 1) {
        // 四种情况
        if (moveNode.nextSibling === undefined) {
          return type === "prev";
        } else if (inNode.nextSibling === undefined) {
          return type === "next";
        } else if (moveNode.nextSibling.id !== inNode.id) {
          return type === "prev";
        } else {
          return type === "next";
        }
      }
    },
    /**
     * 页码的渲染方法
     **/
    treeRenderContent(createElement, { node, data, store }) {
      return createElement("span", [
        createElement("span", {}, "第 " + data.$treeNodeId + " 页"),
      ]);
    },
    /**
     * 页码拖拽成功
     * @param before 被拖拽节点对应的 Node
     * @param after 结束拖拽时最后进入的节点
     * @param inner 被拖拽节点的放置位置
     * @param event 事件
     **/
    treeNodeDrop(before, after, inner, event) {
      // console.log(before)
      // console.log(after)
      // console.log(inner)
      // console.log(event)
      // console.log('互换之后---->>', this.templateData)
    },
    /**
     * 页码点击事件
     * @param par1 传递给 data 属性的数组中该节点所对应的对象
     * @param par2 节点对应的 Node
     * @param par3 节点组件本身
     **/
    treeNodeClick(par1, par2, par3) {
      this.vueDragResizeDeactivated(); // 取消激活某个组件
      this.workingData = par1; // 替换现在的页
    },
    /**
     * 添加一页
     **/
    addPage() {
      this.templateData.pages.push({
        index: this.templateData.pages.length.toString(),
        background_img: "",
        items: [],
      });
    },
    /**
     * 删除一页
     **/
    deletePage() {
      this.$confirm("此操作将删除该页, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          for (let i = 0; i < this.templateData.pages.length; i++) {
            if (this.workingData.index === this.templateData.pages[i].index) {
              this.templateData.pages.splice(i, 1);
              if (this.templateData.pages.length > 0) {
                this.workingData = this.templateData.pages[0];
                this.$refs.pageTree.setCurrentKey(
                  this.templateData.pages[0].index
                ); // 设置默认勾选的页码
              } else {
                this.templateData.pages = [];
                setTimeout(() => {
                  this.templateData.pages.push({
                    index: this.templateData.pages.length.toString(),
                    background_img: "",
                    items: [],
                  });
                  this.workingData = this.templateData.pages[0];
                  this.$refs.pageTree.setCurrentKey(
                    this.templateData.pages[0].index
                  ); // 设置默认勾选的页码
                }, 1000);
              }
              return;
            }
          }
        })
        .catch(() => {});
    },
    /**
     * 选择了图片边框
     * @param item
     */
    selectedImg(item) {
      if (
        this.tempActivatedItem !== null &&
        this.tempActivatedItem.type === 1
      ) {
        this.tempActivatedItem.theme = item.resourcesSrc;
      } else {
        this.workingData.items.push({
          type: 1,
          theme: item.resourcesSrc,
          src: "logo/logo3.png",
          // src: '',
          width: 100,
          height: 100,
          top: 0,
          left: 0,
          dynamicEffect: "",
          dynamicDuration: "",
          zIndex: 1,
          isActive: false,
        });
      }
    },
    /**
     * 选择视频
     * @param item
     **/
    selectedVideo(item) {
      if (
        this.tempActivatedItem !== null &&
        this.tempActivatedItem.type === 3
      ) {
        this.tempActivatedItem.theme = item.resourcesSrc;
      } else {
        this.workingData.items.push({
          type: 3,
          theme: item.resourcesSrc,
          src: "microPageModulesResources/video/template/template1/video1.mp4",
          width: 278,
          height: 160,
          top: 180,
          left: 20,
          dynamicEffect: "fadeInDown",
          dynamicDuration: 1,
          dynamicDelay: 0,
          zIndex: 1,
          isActive: false,
        });
      }
    },
    /**
     * 选择电话
     * @param item
     **/
    selectedPhone(item) {
      if (
        this.tempActivatedItem !== null &&
        this.tempActivatedItem.type === 4
      ) {
        this.tempActivatedItem.theme = item.resourcesSrc;
      } else {
        this.workingData.items.push({
          type: 4,
          theme: item.resourcesSrc,
          name: "联系人名字",
          text: "188****8888",
          text_color: "#FFF",
          text_size: 20,
          width: 220,
          height: 60,
          top: 120,
          left: 50,
          dynamicEffect: "fadeInDown",
          dynamicDuration: 1,
          zIndex: 1,
          isActive: false,
        });
      }
    },
    /**
     * 选择链接
     * @param item
     **/
    selectedLink(item) {
      if (
        this.tempActivatedItem !== null &&
        this.tempActivatedItem.type === 4
      ) {
        this.tempActivatedItem.theme = item.resourcesSrc;
      } else {
        this.workingData.items.push({
          type: 5,
          theme: item.resourcesSrc,
          name: "tootootool",
          text: "https://www.tootootool.com",
          text_color: "#FFF",
          text_size: 20,
          width: 220,
          height: 40,
          top: 120,
          left: 50,
          dynamicEffect: "fadeInDown",
          dynamicDuration: 1,
          zIndex: 1,
          isActive: false,
        });
      }
    },
    /**
     * 选择地图
     * @param item
     **/
    selectedMap(item) {
      if (
        this.tempActivatedItem !== null &&
        this.tempActivatedItem.type === 4
      ) {
        this.tempActivatedItem.theme = item.resourcesSrc;
      } else {
        this.workingData.items.push({
          type: 6,
          theme: item.resourcesSrc,
          lat: 39.915,
          lng: 116.404,
          text_color: "#FFF",
          text_size: 20,
          width: 220,
          height: 160,
          top: 164,
          left: 50,
          dynamicEffect: "fadeInDown",
          dynamicDuration: 1,
          zIndex: 1,
          isActive: false,
        });
      }
    },
    /**
     * 选择背景音乐
     * @param item
     **/
    selectedMusic(item) {
      this.templateData.background_music = "";
      if (item.resourcesSrc !== "") {
        if (this.audioInstance) {
          this.audioInstance.pause();
        }
        this.templateData.background_music = `microPageModulesResources/musics/${item.resourcesSrc}.mp3`;
        if (this.audioInstance) {
          this.$nextTick(() => {
            this.audioInstance.play();
          });
        }
      }
    },
    /**
     * 播放或暂停背景音乐
     **/
    playOrPauseMusic() {
      // 判断背景音乐
      if (this.templateData.background_music) {
        if (this.audioInstance === null) {
          this.audioInstance = this.$refs.audio;
        }
        if (this.audioInstance.paused) {
          this.audioInstance.play();
          this.audioPlaying = true;
        } else {
          this.audioInstance.pause();
          this.audioPlaying = false;
        }
      }
    },
    /**
     * 选择了文字边框
     * @param item
     */
    selectedText(item) {
      if (
        this.tempActivatedItem !== null &&
        this.tempActivatedItem.type === 2
      ) {
        this.tempActivatedItem.theme = item.resourcesSrc;
      } else {
        this.workingData.items.push({
          type: 2,
          theme: item.resourcesSrc,
          text: "请输入文字",
          text_color: "#FFF",
          text_size: 14,
          width: 75,
          height: 20,
          top: 100,
          left: 100,
          dynamicEffect: "",
          dynamicDuration: "",
          zIndex: 1,
          isActive: false,
        });
      }
    },
    /**
     * 选择了背景
     * @param item
     */
    selectedBackgroundImg(item) {
      this.workingData.background_img = item.resourcesSrc;
    },
    /**
     * 组件重置大小
     * @param newRect
     */
    resize(newRect) {
      if (this.tempActivatedItem !== null) {
        this.tempActivatedItem.width = newRect.width;
        this.tempActivatedItem.height = newRect.height;
        this.tempActivatedItem.top = newRect.top;
        this.tempActivatedItem.left = newRect.left;
      }
    },
    /**
     * 点击事件
     */
    vueDragResizeClicked() {},
    /**
     * 拖动事件
     */
    vueDragResizeDragging(newRect) {
      if (this.tempActivatedItem !== null) {
        this.tempActivatedItem.width = newRect.width;
        this.tempActivatedItem.height = newRect.height;
        this.tempActivatedItem.top = newRect.top;
        this.tempActivatedItem.left = newRect.left;
      }
    },
    /**
     * 激活事件
     */
    vueDragResizeActivated(item) {
      if (this.tempActivatedItem !== null) {
        this.tempActivatedItem.isActive = false;
      }
      for (let i = 0; i < this.workingData.items.length; i++) {
        this.workingData.items[i].isActive = false;
      }
      this.tempActivatedItem = item; // 保存激活的项
      this.tempActivatedItem.isActive = true;
    },
    /**
     * 取消激活事件
     */
    vueDragResizeDeactivated() {
      if (this.tempActivatedItem !== null) {
        this.tempActivatedItem.isActive = false;
        this.tempActivatedItem = null; // 清空激活的项
      }
    },
    /**
     * 监听激活的项的变化
     **/
    tempActivatedItemChange() {
      if (this.tempActivatedItem !== null) {
        switch (this.tempActivatedItem.type) {
          case 1:
            this.itemAttr.type = "图片";
            break;
          case 2:
            this.itemAttr.type = "文字";
            break;
          case 3:
            this.itemAttr.type = "视频";
            break;
          case 4:
            this.itemAttr.type = "电话";
            break;
          case 5:
            this.itemAttr.type = "网址";
            break;
          case 6:
            this.itemAttr.type = "地图导航";
            break;
        }
      } else {
        this.itemAttr.type = ""; // 清空属性
      }
    },
    /**
     *元素水平居中
     */
    horizonCenter() {
      if (this.tempActivatedItem !== null) {
        let itemWidth = this.tempActivatedItem.width / 2;
        this.tempActivatedItem.left = 320 / 2 - itemWidth;
      }
    },
    /**
     *元素垂直居中
     */
    verticalCenter() {
      if (this.tempActivatedItem !== null) {
        let itemHeight = this.tempActivatedItem.height / 2;
        this.tempActivatedItem.top = 486 / 2 - itemHeight;
      }
    },
    /**
     * 图片上传成功事件
     */
    imgUploadSuccess(res, file) {
      if (
        this.tempActivatedItem !== null &&
        this.tempActivatedItem.type === 1
      ) {
        this.tempActivatedItem.src = res.data.replace(/\\/g, "/");
      }
    },
    /**
     * 视频上传成功事件
     */
    videoUploadSuccess(res, file) {
      if (
        this.tempActivatedItem !== null &&
        this.tempActivatedItem.type === 3
      ) {
        this.tempActivatedItem.src = res.data.replace(/\\/g, "/");
      }
    },
    /**
     * 图片上传前事件
     */
    beforeImgUpload(file) {
      const isJPG = /\.(jpg|jpeg|png|GIF|JPG|PNG)$/.test(file.name);
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG、PNG、GIF 等格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    /**
     * 视频上传前事件
     */
    beforeVideoUpload(file) {
      const isVideo = /\.(mp4|ogg|MP4|OGG)$/.test(file.name);
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isVideo) {
        this.$message.error("上传视频只能是 MP4或者OGG 格式!");
      }
      if (!isLt10M) {
        this.$message.error("上传视频大小不能超过 10MB!");
      }
      return isVideo && isLt10M;
    },
    /**
     * 删除组件
     * @param index
     */
    deleteModule(index) {
      this.$confirm("此操作将删除该组件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.tempActivatedItem.isActive = false;
          this.tempActivatedItem = null; // 清空激活的项
          this.workingData.items.splice(index, 1); // 删除数组中自己的元素
        })
        .catch(() => {});
    },
    /**
     * 保存并发布
     */
    saveAndPublish() {
      this.uploadData(); // 新增或修改
    },
    /**
     * 新增或修改
     * @param
     */
    async uploadData() {
      // TODO 保存到数据库
      let arr = localStorage.getItem("myPage");
      if (arr === null) {
        arr = [];
      } else {
        arr = JSON.parse(arr);
      }
      if (this.$route.query.id) {
        let index = arr.findIndex((t) => t.id === this.$route.query.id);
        arr[index].content = this.templateData;
      } else {
        arr.push({
          id: Date.now() + "",
          content: this.templateData,
        });
      }
      localStorage.setItem("myPage", JSON.stringify(arr));
      this.$message({
        message: "保存成功",
        type: "success",
      });
    },
  },
  destroyed() {},
};
</script>

<style lang='scss' scoped>
@import "@/assets/css/phoneTheme.scss";
@import "@/assets/css/linkTheme.scss";
#microPageCreate {
  width: 100%;
  height: 100%;
  position: relative;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  .zonetoolsBox {
    width: 300px;
    height: 100%;
    position: relative;
    .tools-box {
      width: 100%;
      height: 545px;
      position: absolute;
      top: 50%;
      left: 0;
      border: 1px solid #cccccc;
      border-left: none;
      border-top-right-radius: 10px;
      border-bottom-right-radius: 10px;
      transform: translateY(-50%);
    }
  }
  .zone-operation {
    width: -moz-calc(100% - 600px);
    width: -webkit-calc(100% - 600px);
    width: calc(100% - 600px);
    min-width: 486px;
    height: 100%;
    position: relative;
    .phone-div {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      .phone-top {
        width: 100%;
        height: 30px;
        background-color: #e0e0e0;
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
        position: relative;
        .phone-camera {
          width: 8px;
          height: 8px;
          border-radius: 50%;
          position: absolute;
          left: 20%;
          top: 50%;
          transform: translateY(-50%);
          background-color: #ccc;
        }
        .phone-speaker {
          width: 50px;
          height: 6px;
          border-radius: 10px;
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          background-color: #ccc;
        }
      }
      .phone-middle {
        width: 320px;
        height: 486px;
        border-left: 1px solid #e0e0e0;
        border-right: 1px solid #e0e0e0;
      }
      #working_space {
        .background_music_icon {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          position: absolute;
          right: 0;
          z-index: 999;
          cursor: pointer;
          i {
            display: block;
            margin-top: 9px;
            margin-left: 9px;
            width: 28px;
            height: 28px;
            background: url(../../assets/images/audio.png) no-repeat right 0;
          }
        }
        .background_music_icon_play {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          position: absolute;
          right: 0;
          z-index: 999;
          cursor: pointer;
          i {
            display: block;
            margin-top: 9px;
            margin-left: 9px;
            width: 28px;
            height: 28px;
            background: url(../../assets/images/audio.png) no-repeat left 0;
            -webkit-transform: rotate(360deg);
            animation: rotation 3s linear infinite;
            -moz-animation: rotation 3s linear infinite;
            -webkit-animation: rotation 3s linear infinite;
            -o-animation: rotation 3s linear infinite;
          }
        }
        @-webkit-keyframes rotation {
          from {
            -webkit-transform: rotate(0deg);
          }
          to {
            -webkit-transform: rotate(360deg);
          }
        }
        @-moz-keyframes rotation {
          from {
            -moz-transform: rotate(0deg);
          }
          to {
            -moz-transform: rotate(360deg);
          }
        }
        @-o-keyframes rotation {
          from {
            o: rotate(0deg);
          }
          to {
            o: rotate(360deg);
          }
        }
        @keyframes rotation {
          from {
            transform: rotate(0deg);
          }
          to {
            transform: rotate(360deg);
          }
        }
        .item_space {
          width: 100%;
          height: 100%;
          position: relative;
          background-size: 100% 100%;
          background-repeat: no-repeat;
          overflow: hidden;
        }
        .module-images {
          background-repeat: no-repeat;
          background-size: 100% 100%;
          overflow: hidden;
        }
        .module-text {
          background-repeat: no-repeat;
          background-size: 100% 100%;
          overflow: hidden;
          padding: 2px 5px;
          display: inline-block;
          word-wrap: break-word;
          word-break: normal;
        }
        .exitEditMode {
          position: absolute;
          right: -24px;
          top: -24px;
          cursor: pointer;
          font-size: 12px;
          color: rgb(255, 255, 255);
          background-color: rgb(204, 204, 204);
          font-style: unset;
          padding: 2px 5px;
          border-radius: 5px;
          -webkit-transform: scale(0.8, 0.8);
          -moz-transform: scale(0.8, 0.8);
          -o-transform: scale(0.8, 0.8);
          transform: scale(0.8, 0.8);
        }
        .deleteBtn {
          position: absolute;
          width: 20px;
          height: 20px;
          padding: 0;
          font-size: 14px;
          text-align: center;
          line-height: 20px;
          left: 50%;
          transform: translateX(-50%);
          top: -25px;
        }
      }
      .phone-bottom {
        width: 100%;
        height: 30px;
        background-color: #e0e0e0;
        border-bottom-left-radius: 10px;
        border-bottom-right-radius: 10px;
        position: relative;
        .phone-botton {
          width: 50px;
          height: 20px;
          border-radius: 10px;
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          background-color: #ccc;
        }
      }
    }
  }
  .zone-attributes {
    width: 300px;
    height: 100%;
    position: relative;
    .tools-box {
      width: 100%;
      height: 545px;
      position: absolute;
      top: 50%;
      right: 0;
      border: 1px solid #cccccc;
      border-right: none;
      border-top-left-radius: 10px;
      border-bottom-left-radius: 10px;
      transform: translateY(-50%);
    }
  }
}
</style>

<style lang='scss'>
#microPageCreate {
  .zonetoolsBox {
    .tools-box {
      .el-card__body {
        padding: 0;
        height: -moz-calc(100% - 58px);
        height: -webkit-calc(100% - 58px);
        height: calc(100% - 58px);
        border-top: none;
        .el-tabs__content {
          height: -moz-calc(100% - 30px);
          height: -webkit-calc(100% - 30px);
          height: calc(100% - 30px);
          padding-right: 0;
          padding-left: 0;
          .el-tab-pane {
            height: 100%;
            padding-right: 15px;
          }
        }
      }
    }
  }
  .zone-attributes {
    .el-card__body {
      padding: 0;
      height: -moz-calc(100% - 58px);
      height: -webkit-calc(100% - 58px);
      height: calc(100% - 58px);
      border-top: none;
      .el-tabs__content {
        overflow-y: auto;
        height: -moz-calc(100% - 75px);
        height: -webkit-calc(100% - 75px);
        height: calc(100% - 75px);
      }
      .el-tabs__content::-webkit-scrollbar-track-piece {
        // 滚动条凹槽的颜色，还可以设置边框属性
        background-color: #f8f8f8;
      }
      .el-tabs__content::-webkit-scrollbar {
        // 滚动条的宽度
        width: 6px;
        height: 6px;
      }
      .el-tabs__content::-webkit-scrollbar-thumb {
        // 滚动条的设置
        background-color: #dddddd;
        background-clip: padding-box;
        min-height: 28px;
        border-top-left-radius: 5px;
        border-bottom-left-radius: 5px;
      }
      .el-tabs__content::-webkit-scrollbar-thumb:hover {
        background-color: #bbb;
      }
      .page-list {
        .el-tree-node {
          .el-tree-node__content {
            height: 36px;
            line-height: 36px;
            .el-tree-node__expand-icon {
              display: none;
              .el-tree-node__label {
                padding-left: 5px;
              }
            }
          }
        }
      }
    }
  }
}
</style>

